﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SSN.WebFramework.Security
{
    public static class PageSecurityManager
    {
        private static PageSecurityCache _PageSecurityCache = new PageSecurityCache();

        /// <summary>
        /// Indicates whether a user has access to view a page.
        /// </summary>
        /// <param name="page">Page tp verify.</param>
        /// <returns></returns>
        public static bool CanView(AuthPage page)
        {
            List<PageSecurity> sec = _PageSecurityCache[page.Request.Url.LocalPath];
            if (sec == null || sec.Count == 0)
            {
                return true;
            }

            foreach (PageSecurity ps in sec)
            {
                switch (ps.PrincipleType)
                {
                    case PrincipleType.Role:
                        if (page.SecurityManager.SecurityContext.IsInRole(ps.Principle) && ps.AccessLevel >= AccessLevel.View)
                        {
                            return true;
                        }
                        break;

                    case PrincipleType.User:
                        if (page.SecurityManager.SecurityContext.userid == ps.Principle && ps.AccessLevel >= AccessLevel.View)
                        {
                            return true;
                        }

                        break;
                }
            }

            return false;
        }

        /// <summary>
        /// Invalidates a page's security.
        /// </summary>
        /// <param name="path"></param>
        public static void PurgePageSecurity(string path)
        {
            _PageSecurityCache.DecacheItem(path);
        }
    }
}
